package com.ruoyi.web.controller.train;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.PracticeInfoReport;
import com.ruoyi.system.domain.TrainingCadet;
import com.ruoyi.system.domain.TrainingInfoReport;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.ITrainingCadetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 培训学员信息Controller
 *
 * @author dp
 * @date 2023-11-27
 */
@Api(tags = {"培训学员信息管理"})
@RestController
@RequestMapping("/train/cadet")
public class TrainingCadetController extends BaseController {

    @Autowired
    private ITrainingCadetService trainingCadetService;
    @Autowired
    TokenService tokenService;
    @Autowired
    ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;

    /**
     * 查询培训学员信息列表
     */
    @ApiOperation(value = "培训学员信息列表", notes = "查询培训学员信息列表详情", tags = {"培训学员信息管理"})
    //@PreAuthorize("@ss.hasPermi('train:cadet:list')")
    @GetMapping("/list")
    public TableDataInfo list(TrainingCadet trainingCadet) {
        startPage();
        List<TrainingCadet> list = trainingCadetService.selectTrainingCadetList(trainingCadet);
        return getDataTable(list);
    }

    /**
     * 导出培训学员信息列表
     */
    @ApiOperation(value = "培训学员信息列表导出", notes = "导出培训学员信息列表", tags = {"培训学员信息管理"})
    //@PreAuthorize("@ss.hasPermi('train:cadet:export')")
    @Log(title = "培训学员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TrainingCadet trainingCadet) {
        List<TrainingCadet> list = trainingCadetService.selectTrainingCadetList(trainingCadet);
        ExcelUtil<TrainingCadet> util = new ExcelUtil<TrainingCadet>(TrainingCadet.class);
        util.exportExcel(response, list, "培训学员信息数据");
    }

    /**
     * 获取培训学员信息详细信息
     */
    @ApiOperation(value = "获取培训学员信息详细信息", notes = "获取培训学员信息详细信息详情", tags = {"培训学员信息管理"})
    //@PreAuthorize("@ss.hasPermi('train:cadet:query')")
    @GetMapping(value = "/{cadetId}")
    public AjaxResult getInfo(@PathVariable("cadetId") String cadetId) {
        return success(trainingCadetService.selectTrainingCadetByCadetId(cadetId));
    }

    /**
     * 获取培训对象当前扩展信息
     */
    @ApiOperation(value = "获取培训对象当前扩展信息", notes = "获取培训对象当前扩展信息", tags = {"培训学员信息管理"})
    //@PreAuthorize("@ss.hasPermi('train:cadet:query')")
    @GetMapping(value = "/nowExpandInfo/{cadetId}")
    public AjaxResult getNowExpandInfo(@PathVariable("cadetId") String cadetId) {
        return success(trainingCadetService.selectNowExpandInfo(cadetId));
    }

    /**
     * 新增培训学员信息
     */
    @ApiOperation(value = "新增培训学员信息", notes = "新增培训学员信息详情", tags = {"培训学员信息管理"})
    //@PreAuthorize("@ss.hasPermi('train:cadet:add')")
    @Log(title = "培训学员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(HttpServletRequest request, @RequestBody TrainingCadet trainingCadet) {
        Long userId = tokenService.getLoginUser(request).getUser().getUserId();
        trainingCadetService.completeData(trainingCadet, userId, 1);

        //同步添加用户
        SysUser user = new SysUser();
        user.setPassword("abc@123..");
        user.setUserName(trainingCadet.getCadetCode());
        user.setNickName(trainingCadet.getCadetName());
        user.setPhonenumber(trainingCadet.getTelephone());
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getNickName() + "'失败，登录账号[" + user.getUserName() + "]已存在,不允许重复添加！");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getNickName() + "'失败，手机号码[" + user.getPhonenumber() + "]已有用户在使用！");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getNickName() + "'失败，邮箱账号[" + user.getEmail() + "]已有用户在使用");
        }

        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userService.insertUser(user);

        //根据用户编码获取用户id
        SysUser sysUser = userService.selectUserByUserName(user.getUserName());
        trainingCadet.setUserId(sysUser.getUserId().toString());

        //同步添加用户角色
        //培训对象角色id为5
        Long roleId = 5L;
        Long[] userIds = new Long[1];
        userIds[0] = user.getUserId();
        roleService.checkRoleDataScope(roleId);
        roleService.insertAuthUsers(roleId, userIds);

        return toAjax(trainingCadetService.insertTrainingCadet(trainingCadet));
    }

    /**
     * 修改培训学员信息
     */
    @ApiOperation(value = "修改培训学员信息", notes = "修改培训学员信息详情", tags = {"培训学员信息管理"})
    //@PreAuthorize("@ss.hasPermi('train:cadet:edit')")
    @Log(title = "培训学员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(HttpServletRequest request, @RequestBody TrainingCadet trainingCadet) {
        Long userId = tokenService.getLoginUser(request).getUser().getUserId();
        trainingCadetService.completeData(trainingCadet, userId, 2);
        return toAjax(trainingCadetService.updateTrainingCadet(trainingCadet));
    }

    /**
     * 删除培训学员信息
     */
    @ApiOperation(value = "删除培训学员信息", notes = "删除培训学员信息详情", tags = {"培训学员信息管理"})
    //@PreAuthorize("@ss.hasPermi('train:cadet:remove')")
    @Log(title = "培训学员信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{cadetIds}")
    public AjaxResult remove(@PathVariable String[] cadetIds) {
        return toAjax(trainingCadetService.deleteTrainingCadetByCadetIds(cadetIds));
    }

    /**
     * 实践内容统计
     */
    @ApiOperation(value = "获取实践内容统计", notes = "培训内容统计", tags = {"培训学员信息管理"})
    @GetMapping(value = "/practiceInfo")
    public TableDataInfo practiceInfo( @RequestParam("baseId") Long baseId,@RequestParam("startTime") Date startTime, @RequestParam("endTime") Date endTime) {
        startPage();
        List<PracticeInfoReport> list = trainingCadetService.selectPracticeInfoReport(baseId, startTime, endTime);
        return getDataTable(list);
    }

    /**
     * 培训内容统计
     */
    @ApiOperation(value = "获取培训内容统计", notes = "培训内容统计", tags = {"培训学员信息管理"})
    @GetMapping(value = "/trainingInfo")
    public TableDataInfo trainingInfo( @RequestParam("baseId") Long baseId,@RequestParam("startTime") Date startTime, @RequestParam("endTime") Date endTime) {
        startPage();
        List<TrainingInfoReport> list = trainingCadetService.selectTrainingInfoReport(baseId, startTime, endTime);
        return getDataTable(list);
    }
}
